package com.producteev4j.model.request;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: jcarrey
 * Date: 25/06/11
 * Time: 20:01
 * To change this template use File | Settings | File Templates.
 */
public class ProducteevParamUtil {


    public static boolean isDate(final Object o) {
        if (o instanceof Date) {
            return true;
        } else if (o instanceof Calendar) {
            return true;
        } else {
            return false;
        }
    }

    public static Date getDate(final Object o) {
        if (o instanceof Date) {
            return (Date) o;
        } else if (o instanceof Calendar) {
            return ((Calendar) o).getTime();
        }

        return null;

    }


    private static String encode(final String o) {
        try {
            return URLEncoder.encode(o, "utf-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    public static String toString(final Object value) {
        if (isDate(value)) {
            return ProducteevDateUtil.formatDateRFC(getDate(value));
        } else {
            return String.valueOf(value);
        }
    }

    public static String encode(final Object value) {
        return encode(toString(value));
    }

}
